<?php
// 根据devid和devmac生成token的接口

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

// 引入数据库配置
require_once 'config.php';

// 只处理POST请求
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['status' => 'error', 'message' => '只允许POST请求']);
    exit;
}

// 获取POST数据
$input = file_get_contents('php://input');
$data = json_decode($input, true);

// 检查必要参数
if (!$data || !isset($data['devid']) || !isset($data['devmac'])) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => '缺少必要参数: devid 和 devmac']);
    exit;
}

$devid = $data['devid'];
$devmac = $data['devmac'];

// 验证参数
if (empty($devid) || empty($devmac)) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'devid 和 devmac 不能为空']);
    exit;
}

try {
    // 获取数据库连接
    $pdo = getDBConnection();
    
    // 检查设备是否已存在
    $checkStmt = $pdo->prepare("SELECT * FROM devices WHERE devid = ? AND devmac = ?");
    $checkStmt->execute([$devid, $devmac]);
    $existingDevice = $checkStmt->fetch(PDO::FETCH_ASSOC);
    
    if ($existingDevice) {
        // 设备已存在，返回现有token
        echo json_encode([
            'status' => 'success',
            'message' => '设备已存在，返回现有Token',
            'data' => [
                'devid' => $existingDevice['devid'],
                'devmac' => $existingDevice['devmac'],
                'token' => $existingDevice['token'],
                'created_at' => $existingDevice['created_at']
            ]
        ]);
        exit;
    }
    
    // 设备不存在，生成新的token
    $token = md5($devid . $devmac . time());
    
    // 插入新设备信息到数据库
    $insertStmt = $pdo->prepare("INSERT INTO devices (devid, devmac, token) VALUES (?, ?, ?)");
    $insertStmt->execute([$devid, $devmac, $token]);
    
    // 返回成功响应
    echo json_encode([
        'status' => 'success',
        'message' => 'Token生成成功并已存储',
        'data' => [
            'devid' => $devid,
            'devmac' => $devmac,
            'token' => $token,
            'created_at' => date('Y-m-d H:i:s')
        ]
    ]);
    
} catch (Exception $e) {
    // 错误处理
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => 'Token生成失败: ' . $e->getMessage()]);
}
?>